package day08.homework;

public class StringTest {

    public static void main(String[] args) {
        String oldStr = "abcdessde";
        System.out.println(delStr(oldStr,"de"));

        String str1 = "abcfdfdfdxoooooo";
        String str2 = "fdfdfdqedsdaoooooofdfdfdfdf";

        String str3 = "abcfdfdfdxoooooooooo";
        String str4 = "fdfdfdqedsdaooooooooooofdfdfdfdf";

        System.out.println(commonStr(str3, str4));
    }

    /**
     * 根据指定的字符串进行删除
     * @param oldStr
     * @param target
     * @return
     */
    public static String delStr(String oldStr,String target){
        //1. 指定递归出口
        if(!oldStr.contains(target))
            return oldStr;
        //2. 递归调用自己
        //2-1. 找出target在oldStr中第一次出现的位置
        int startIndex = oldStr.indexOf(target);
        int endIndex = startIndex+target.length();
        //abcdebc
        //StringBuilder delete(start,end);// [start,end);
        StringBuilder result = new StringBuilder(oldStr).delete(startIndex,endIndex);
        return delStr(result.toString(),target);
    }

    /**找最大长度的公串
     * 默认的是str1的长度要小于str2
     * @param str1
     * @param str2
     * @return
     */
    public static StringBuilder commonStr(String str1,String str2){
        StringBuilder x = new StringBuilder();//用来负责存储公串

        //定义一个默认的长度
        int len = 0;
        //确定遍历长度小的string
        for (int i = 0; i < str1.length(); i++) {
            for (int j=i+1;j<=str1.length();j++){
                //取出str1的各种子串
                String subStr = str1.substring(i,j);

                //取出子串的长度
                int subStrLen = subStr.length();
                //System.out.println(subStr);
                //判断str2中是否包含subStr - 公串
                if(str2.contains(subStr) && subStrLen>len){
                    //后面的子串长度比x中曾经存储的字符串的长度要长
                    //清空一下StringBuilder
                    x.delete(0,x.capacity());

                    x.append(subStr+" ");

                    len = subStrLen;
                }else if(str2.contains(subStr) && subStrLen==len){
                    x.append(subStr+" ");
                }
            }
        }
        return x;
    }


}